using GroupSix.Domain.Repositories;
using GroupSix.Domain.Entity.App;
using GroupSix.Domain.common;
using GroupSix.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace GroupSix.Infrastructure.Reposoitories;

/// <summary>
/// 系统设置仓储实现
/// </summary>
public class SystemSettingRepository : EfRepository<GsSystemSetting>, ISystemSettingRepository
{
    public SystemSettingRepository(GroupSixDbContext context) : base(context)
    {
    }

    /// <summary>
    /// 根据键获取设置
    /// </summary>
    public async Task<GsSystemSetting?> GetByKeyAsync(string settingKey)
    {
        return await _tb.FirstOrDefaultAsync(s => s.SettingKey == settingKey);
    }

    /// <summary>
    /// 根据分组获取设置列表
    /// </summary>
    public async Task<List<GsSystemSetting>> GetByGroupAsync(string group)
    {
        return await _tb
            .Where(s => s.Group == group)
            .OrderBy(s => s.SortOrder)
            .ThenBy(s => s.SettingKey)
            .ToListAsync();
    }

    /// <summary>
    /// 分页查询系统设置
    /// </summary>
    public async Task<PageResult<GsSystemSetting>> GetPagedAsync(PageRequest query)
    {
        var queryable = _tb.AsQueryable();

        // 排序
        queryable = queryable.OrderBy(s => s.Group)
            .ThenBy(s => s.SortOrder)
            .ThenBy(s => s.SettingKey);

        var totalCount = await queryable.CountAsync();

        var items = await queryable
            .Skip((query.PageIndex - 1) * query.PageSize)
            .Take(query.PageSize)
            .ToListAsync();

        return new PageResult<GsSystemSetting>
        {
            Items = items,
            TotalCount = totalCount,
            PageIndex = query.PageIndex,
            PageSize = query.PageSize
        };
    }

    /// <summary>
    /// 检查设置键是否存在
    /// </summary>
    public async Task<bool> ExistsByKeyAsync(string settingKey, Guid? excludeId = null)
    {
        var query = _tb.Where(s => s.SettingKey == settingKey);
        
        if (excludeId.HasValue)
        {
            query = query.Where(s => s.Id != excludeId.Value);
        }

        return await query.AnyAsync();
    }

    /// <summary>
    /// 批量更新设置
    /// </summary>
    public async Task<bool> UpdateBatchAsync(List<GsSystemSetting> settings)
    {
        try
        {
            foreach (var setting in settings)
            {
                _tb.Update(setting);
            }

            await _db.SaveChangesAsync();
            return true;
        }
        catch
        {
            return false;
        }
    }
} 